//
//  UtilitiesFunctions.m
//  BulltinBoard
//
//  Created by joker on 15/6/26.
//  Copyright (c) 2015年 joker. All rights reserved.
//

#import "UtilitiesFunctions.h"
#import <UIKit/UIKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <Foundation/Foundation.h>


#import "ASIFormDataRequest.h"
#import "ASIHTTPRequest.h"
#import "ASIHTTPRequestConfig.h"

@implementation UtilitiesFunctions

+(NSURL *)serverSite{
#ifdef _FOR_TEST
    return [NSURL URLWithString:@"https://192.168.1.24/"];//这个测试地址需要HTTPS验证
#else
    return [NSURL URLWithString:@"https://oa.jiuan.com:4433/"];
#endif
}
+(void) showLogResultTitle:(NSString *) showTitle  withMessage:(NSString *)willShowMessage {
    
    UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:showTitle message:willShowMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alertView show];
}
+ (NSString *)getMd5_32Bit_String:(NSString *)srcString{
    const char *cStr = [srcString cStringUsingEncoding:NSUTF16StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (CC_LONG)[srcString length]*2, result );
    return [NSString
            stringWithFormat: @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1],result[2], result[3],result[4], result[5],result[6], result[7],
            result[8], result[9],result[10], result[11],result[12], result[13],result[14], result[15]
            ];
}
+(NSString *)logInOAWithUserName:(NSString *)userName AndUserPasswords:(NSString *)userPassword {
    
    NSURL *queryURL=[NSURL URLWithString:@"MobileOfficeAutomationAPI/LoginWeb.ashx" relativeToURL:[self serverSite]];

    NSString *md5UserPasswords=[self getMd5_32Bit_String:userPassword];
    
    NSDictionary *userInfo=@{@"LogonName": userName,@"PassWord":md5UserPasswords };
    
    NSData *contentData=[NSJSONSerialization dataWithJSONObject:userInfo options:kNilOptions error:nil];
    
    NSString *contentString=[[NSString alloc] initWithData:contentData encoding:NSUTF8StringEncoding];

#ifndef _USE_THIRDPART_FRAMEWORK_COMMUNICATION
        ////////////////////////////原生sdk调用/////////////////////////////////////////////
    NSString *jsonString=[NSString stringWithFormat:@"content=%@",contentString];
    
    NSData *jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
        //设置http请求
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:queryURL];
    [request setHTTPMethod:@"POST"]; //设置请求方式为POST
    [request setHTTPBody:jsonData]; //设置发送的数据
    
    NSURLResponse *urlRespond;//用于接收POST请求的返回数据
    NSError *error; //用于记录服务器的返回错误信息
    
        //连接服务器，并返回请求数据
    NSData *respond=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlRespond error:&error];
#else
        //////////////////////////////////////使用第三方库/////////////////////////
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:queryURL];
    [request setAuthenticationScheme:@"https"];
    [request setValidatesSecureCertificate:NO];
    
    [request setPostValue:contentString forKey:@"content"];
    [request startSynchronous];
    
    NSError *error = [request error];
    NSString *response;
    
    response = [request responseString];
    
        //显示登录请求返回的信息
    NSLog(@"%@",response);
    
    NSData *respond=[response dataUsingEncoding:NSUTF8StringEncoding];

        ///////////////////////////////////////////////////////////////////
#endif
    
    NSString *returnValueJsonString;
    
    if(!error){
        NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData:respond options:NSJSONReadingMutableLeaves error:&error];
        
        NSString *displayString;
        NSString *displayTitle;
        
        
        if(!error)
        {
            switch ([responseDict[@"Result"] integerValue]) {
                case 1:
                    returnValueJsonString=responseDict[@"ReturnValue"];
                    break;
                default:
                    displayTitle=@"请求错误";
                    displayString=[NSString stringWithFormat:@"错误代码:%@\n错误信息:%@",responseDict[@"ResultMessage"],responseDict[@"ReturnValue"]];
                    [self showLogResultTitle:displayTitle withMessage:displayString];
                    break;
            }
            
        }
        else{
            displayTitle=@"解析错误";
            displayString=@"POST请求返回数据不是有效的JSON数据格式!";
            [self showLogResultTitle:displayTitle withMessage:displayString];
        }
            }
    else
    {
        [self showLogResultTitle:@"POST请求返回错误信息" withMessage:[error description]];
    }
    return returnValueJsonString;
}

+(NSString *)getBulltinItemsListWithOAfUserID:(NSString *)OAfUserID AccessKey:(NSString *)AccessKey PageSize: (NSNumber *) PageSize TimeStamp:(NSString *)TimeStamp{
    NSURL *queryURL=[NSURL URLWithString:@"MobileOfficeAutomationAPI/GGBMessageListWeb.ashx" relativeToURL:[self serverSite]];
    
//    NSLog(@"%@",[queryURL absoluteString]);
    
    NSDictionary *userInfo=@{@"OAfUserID": OAfUserID,@"AccessKey":AccessKey,@"PageSize":PageSize,@"TimeStamp":TimeStamp};
    
    NSData *contentData=[NSJSONSerialization dataWithJSONObject:userInfo options:kNilOptions error:nil];
    
    NSString *contentString=[[NSString alloc] initWithData:contentData encoding:NSUTF8StringEncoding];
    
#ifndef _USE_THIRDPART_FRAMEWORK_COMMUNICATION
     ////////////////////////////原生sdk调用/////////////////////////////////////////////
//    NSString *jsonString=[NSString stringWithFormat:@"content=%@",contentString];
//    
//    NSData *jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
//    
//        //设置http请求
//    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:queryURL];
//    [request setHTTPMethod:@"POST"]; //设置请求方式为POST
//    [request setHTTPBody:jsonData]; //设置发送的数据
//    
//    NSURLResponse *urlRespond;//用于接收POST请求的返回数据
//    NSError *error; //用于记录服务器的返回错误信息
//    
//        //连接服务器，并返回请求数据
//    NSData *respond=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlRespond error:&error];
#else
        //////////////////////////////////////使用第三方库/////////////////////////
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:queryURL];
    [request setAuthenticationScheme:@"https"];
    [request setValidatesSecureCertificate:NO];
    
    [request setPostValue:contentString forKey:@"content"];
    [request startSynchronous];
    
    NSError *error = [request error];
    NSString *response;
    
    response = [request responseString];
    NSLog(@"%@",response);
    
    NSData *respond=[response dataUsingEncoding:NSUTF8StringEncoding];
    
        ///////////////////////////////////////////////////////////////////
#endif
    
    NSString *returnValueJsonString;
    
    if(!error){
        NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData:respond options:NSJSONReadingMutableLeaves error:&error];
        
        NSString *displayString;
        NSString *displayTitle;
        
        if(!error)
        {
            switch ([responseDict[@"Result"] integerValue]) {
                case 1:
                    returnValueJsonString=responseDict[@"ReturnValue"];
//                    NSLog(@"Get Bulltin items List: \n%@",responseDict);
                    break;
                default:
                    displayTitle=@"请求错误";
                    displayString=[NSString stringWithFormat:@"错误代码:%@\n错误信息:%@",responseDict[@"ResultMessage"],responseDict[@"ReturnValue"]];
                    [self showLogResultTitle:displayTitle withMessage:displayString];
                    break;
            }
            
        }
        else{
            displayTitle=@"解析错误";
            displayString=@"POST请求返回数据不是有效的JSON数据格式!";
            [self showLogResultTitle:displayTitle withMessage:displayString];
        }
    }
    else
    {
        [self showLogResultTitle:@"POST请求返回错误信息" withMessage:[error description]];
    }
    return returnValueJsonString;
}
+(NSString *)getBulltinItemDetailWithOAfUserID:(NSString *)OAfUserID AndAccessKey:(NSString *)AccessKey PlusOATitleID:(NSString *)OATitleID{
    NSURL *queryURL=[NSURL URLWithString:@"MobileOfficeAutomationAPI/GGBInformationWeb.ashx" relativeToURL:[self serverSite]];
    
    NSDictionary *userInfo=@{@"OAfUserID": OAfUserID,@"AccessKey":AccessKey,@"OAfTitleID":OATitleID };
    
    NSData *contentData=[NSJSONSerialization dataWithJSONObject:userInfo options:kNilOptions error:nil];
    
    NSString *contentString=[[NSString alloc] initWithData:contentData encoding:NSUTF8StringEncoding];
    
#ifndef _USE_THIRDPART_FRAMEWORK_COMMUNICATION
        ////////////////////////////原生sdk调用/////////////////////////////////////////////
//    NSString *jsonString=[NSString stringWithFormat:@"content=%@",contentString];
//    
//    NSData *jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
//    
//        //设置http请求
//    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:queryURL];
//    [request setHTTPMethod:@"POST"]; //设置请求方式为POST
//    [request setHTTPBody:jsonData]; //设置发送的数据
//    
//    NSURLResponse *urlRespond;//用于接收POST请求的返回数据
//    NSError *error; //用于记录服务器的返回错误信息
//    
//        //连接服务器，并返回请求数据
//    NSData *respond=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlRespond error:&error];
#else
        //////////////////////////////////////使用第三方库/////////////////////////
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:queryURL];
    [request setAuthenticationScheme:@"https"];
    [request setValidatesSecureCertificate:NO];
    
    [request setPostValue:contentString forKey:@"content"];
    [request startSynchronous];
    
    NSError *error = [request error];
    NSString *response;
    

    response = [request responseString];
    NSLog(@"%@",response);
    
    NSData *respond=[response dataUsingEncoding:NSUTF8StringEncoding];
    
        ///////////////////////////////////////////////////////////////////
#endif
    
    
    NSString *returnValueJsonString;
    
    if(!error){
        NSDictionary *responseDict=[NSJSONSerialization JSONObjectWithData:respond options:NSJSONReadingMutableLeaves error:&error];
        
        NSString *displayString;
        NSString *displayTitle;
        
        if(!error)
        {
            switch ([responseDict[@"Result"] integerValue]) {
                case 1:
                    returnValueJsonString=responseDict[@"ReturnValue"];
                    break;
                default:
                    displayTitle=@"请求错误";
                    displayString=[NSString stringWithFormat:@"错误代码:%@\n错误信息:%@",responseDict[@"ResultMessage"],responseDict[@"ReturnValue"]];
                    [self showLogResultTitle:displayTitle withMessage:displayString];
                    break;
            }
            
        }
        else{
            displayTitle=@"解析错误";
            displayString=@"POST请求返回数据不是有效的JSON数据格式!";
            [self showLogResultTitle:displayTitle withMessage:displayString];
        }
    }
    else
    {
        [self showLogResultTitle:@"POST请求返回错误信息" withMessage:[error description]];
    }
    return returnValueJsonString;
}

+(NSString *)convertTimestampStringToDisplay:(NSTimeInterval) secondsSince1970{
    
    NSDate *createDate=[NSDate dateWithTimeIntervalSince1970:secondsSince1970];
    
    NSDateFormatter *dateFormatter=[NSDateFormatter new];
    [dateFormatter setDateFormat:@"YYYY/MM/dd   HH:mm:ss"];
    
    NSString *dateString=[dateFormatter stringFromDate:createDate];
    
    return dateString;
}
@end
